package com.hefei.garden.config.token;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: devil
 * @Date: 2022/8/17 23
 * @Description:
 */
@Component
public class TokenUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 创建Token存入Redis
     *
     * @param value
     * @return String
     */
    public String generateToken(String value) {
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, value, 5, TimeUnit.MINUTES);
        return token;
    }


    /**
     * 验证token的合法性
     *
     * @param token
     * @param value
     * @return boolean
     */
    public boolean validToken(String token, String value) {
        String script = "if redis.call('get', KEYS[1]) == KEYS[2] " +
                "then return redis.call('del', KEYS[1]) " +
                "else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        // 执行 Lua 脚本, 保证原子性
        Long result = redisTemplate.execute(redisScript, Arrays.asList(token, value));
        return result != null && result != 0L;
    }


}
